package com.admin.service.ipl;

import com.admin.mapper.AssociateWordsMapper;
import com.admin.service.AssociateWordsService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.es.ApAssociateWords;

import com.usian.model.es.Trie;
import com.usian.model.es.UserSearchDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AssociateWordsServiceImpl extends ServiceImpl<AssociateWordsMapper, ApAssociateWords> implements AssociateWordsService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult search(UserSearchDto dto) {
        if (dto.getPageSize()>50){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        IPage page=new Page(dto.getPageNum(),dto.getPageSize());
          //List<ApAssociateWords> list = list();
        IPage iPage=page(page, Wrappers.<ApAssociateWords>lambdaQuery().like(ApAssociateWords::getAssociateWords,dto.getSearchWords()));
        return ResponseResult.okResult(iPage.getRecords());
    }

    @Override
    public ResponseResult searchv2(UserSearchDto dto) {
         //先从缓存中拿到数据
        String assoStr = redisTemplate.opsForValue().get("associate_list");
        List<ApAssociateWords> apAssociateWords=null;
        if (StringUtils.isNotEmpty(assoStr)){

            //如果缓存中有直接拿到
           apAssociateWords= JSON.parseArray(assoStr,ApAssociateWords.class);
        }else {
            //如果没有  就从数据库获取 添加到redis
            apAssociateWords=list();
            redisTemplate.opsForValue().set("associate_list",JSON.toJSONString(apAssociateWords));
        }
        //创建trie数据结构
        Trie trie = new Trie();
         for (ApAssociateWords apAssociateWords1:apAssociateWords){
             trie.insert(apAssociateWords1.getAssociateWords());
         }

        List<String> ret = trie.startWith(dto.getSearchWords());
        List<ApAssociateWords> redultList = new ArrayList<>();
        for (String s:ret){
            ApAssociateWords aaw = new ApAssociateWords();
            aaw.setAssociateWords(s);
            redultList.add(aaw);
        }

        return ResponseResult.okResult(redultList);
    }
}
